import 'package:cached_network_image/cached_network_image.dart';
import 'package:family_expense/main_view.dart';
import 'package:family_expense/shared/services/data_initialization.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class QuickLogin extends StatefulWidget {
  const QuickLogin({super.key, this.redirectRoute});

  final Widget? redirectRoute;

  @override
  State<QuickLogin> createState() => _QuickLoginState();
}

class _QuickLoginState extends State<QuickLogin> {
  final LocalAuthenticationService _localAuth =
      LocalAuthenticationService.instance;
  final AuthStateService _authStateService = AuthStateService.instance;

  bool _authenticationInProgress = false;

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: _onPopInvokedWithResult,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color.fromARGB(1, 250, 250, 250),
          elevation: 0.0,
        ),
        body: _buildBody(),
      ),
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return Column(
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              '快速登录',
              style: Theme.of(context).textTheme.titleLarge,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20.0),
          ],
        ),
        Expanded(
          child: FutureBuilder<Map<String?, User?>?>(
            future: _authStateService.userCollection,
            builder: (context, snapshot) {
              // Gets saved user collection which contains all users' info.
              // There users enabled quick login feature.
              if (snapshot.connectionState == ConnectionState.done &&
                  snapshot.hasData) {
                // Gets the retrieved user collection.
                final userCollection = snapshot.data!;

                if (userCollection.isNotEmpty) {
                  // Creates a list view to display all these users.
                  return ListView.builder(
                    padding: const EdgeInsets.symmetric(horizontal: 16.0),
                    itemCount: userCollection.length,
                    itemBuilder: (context, index) {
                      // Gets map key by [index].
                      final key = userCollection.keys.elementAt(index);

                      // Gets the user info with [key] and builds [Card] with it.
                      return _buildCard(userCollection[key]!);
                    },
                  );
                } else {
                  return Text(
                    '[无数据]',
                    style: Theme.of(
                      context,
                    ).textTheme.titleSmall!.copyWith(color: Colors.grey),
                    textAlign: TextAlign.center,
                  );
                }
              } else {
                return const Center(child: MyCircularProgressIndicator());
              }
            },
          ),
        ),
      ],
    );
  }

  /// Builds the card for each user.
  Widget _buildCard(User user) {
    return Card(
      margin: const EdgeInsets.only(left: 14.0, right: 14.0, bottom: 14.0),
      elevation: 6.0,
      child: InkWell(
        child: Row(
          // crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            SizedBox(
              width: 100.0,
              height: 60.0,
              child: CachedNetworkImage(
                imageUrl: user.avatarUrl!,
                fit: BoxFit.cover,
              ),
            ),
            const SizedBox(width: 10.0),
            Expanded(
              child: Row(
                children: [
                  SizedBox(
                    width: 150.0,
                    child: Text(
                      user.fullName!,
                      style: const TextStyle(
                        fontSize: 18.0,
                        fontWeight: FontWeight.w400,
                        color: Colors.black87,
                        overflow: TextOverflow.ellipsis,
                      ),
                      softWrap: false,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Expanded(
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: IconButton(
                        icon: const Icon(Icons.clear),
                        color: Colors.red,
                        onPressed: () => _removeQuickLoginInfo(user),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        onTap: () => _quickLogin(user),
      ),
    );
  }

  /// Removes [user] from quick login data.
  Future<void> _removeQuickLoginInfo(User user) async {
    showConfirmDialog(
      context,
      '移除 ${user.fullName}(${user.username!.formatMobilePhoneNumber()}) 的快速登录信息？',
      onConfirm: () async {
        await _authStateService.removeFromUserInfoCollection(user);

        TokenService.removeTokenForUserInCollection(user);

        // Triggers UI to rebuild.
        setState(() {});
      },
    );
  }

  /// Starts quick login with saved user and token data.
  Future<void> _quickLogin(User user) async {
    if (await _localAuth.canCheckFingerprint) {
      setState(() => _authenticationInProgress = true);

      if (await _localAuth.authenticateWithFingerprint(
        biometricHint: '登录 ${user.fullName} 的账号',
      )) {
        setState(() => _authenticationInProgress = false);

        // Saves the user data retrieved from server.
        _authStateService.saveUserInfo(user);

        // Gets the [user]'s token from non-active token collection.
        final token = (await TokenService.getTokenForUserInCollection(user))!;

        // Saves this token as active one.
        await TokenService.saveToken(token);

        if (mounted) {
          // Shows the overlay when loading the data.
          showInProgressOverlay(context, message: '正在登录');
        }

        // Initializes the system data.
        DataInitialization().init(() {
          // Jumping to new route and the login page will be popped.
          // It can prevent user to go back to the login page by pressing back button.
          // Let [MainView] handle the redirection will make user can go back from target view to [MainView].
          // Otherwise when user goes back from target view it only causes app to exit.
          NavigatorHelper.pushAndRemoveUntil(
            context,
            MainView(redirectRoute: widget.redirectRoute),
            (route) => false,
          );
        });
      }
    } else {
      showToast('当前设备不支持指纹识别');
    }
  }

  /// Checks the data before popping.
  void _onPopInvokedWithResult(bool didPop, dynamic result) {
    if (didPop) {
      return;
    }

    if (_authenticationInProgress) {
      _localAuth.cancelAuthentication();
      setState(() => _authenticationInProgress = false);
    } else {
      NavigatorHelper.pop(context);
    }
  }
}
